home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / firefox / components / nsSessionStartup.js < prev    next >
Encoding:
Text File  |  2007-04-03  |  15.0 KB  |  445 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is the nsSessionStore component.
  15.  *
  16.  * The Initial Developer of the Original Code is
  17.  * Simon B├╝nzli <zeniko@gmail.com>
  18.  *
  19.  * Portions created by the Initial Developer are Copyright (C) 2006
  20.  * the Initial Developer. All Rights Reserved.
  21.  *
  22.  * Contributor(s):
  23.  * Dietrich Ayala <autonome@gmail.com>
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the MPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the MPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. /**
  40.  * Session Storage and Restoration
  41.  * 
  42.  * Overview
  43.  * This service reads user's session file at startup, and makes a determination 
  44.  * as to whether the session should be restored. It will restore the session 
  45.  * under the circumstances described below.
  46.  * 
  47.  * Crash Detection
  48.  * The session file stores a session.state property, that 
  49.  * indicates whether the browser is currently running. When the browser shuts 
  50.  * down, the field is changed to "stopped". At startup, this field is read, and
  51.  * if it's value is "running", then it's assumed that the browser had previously
  52.  * crashed, or at the very least that something bad happened, and that we should
  53.  * restore the session.
  54.  * 
  55.  * Forced Restarts
  56.  * In the event that a restart is required due to application update or extension
  57.  * installation, set the browser.sessionstore.resume_session_once pref to true,
  58.  * and the session will be restored the next time the browser starts.
  59.  * 
  60.  * Always Resume
  61.  * This service will always resume the session if the integer pref 
  62.  * browser.startup.page is set to 3.
  63.  */
  64.  
  65. /* :::::::: Constants and Helpers ::::::::::::::: */
  66.  
  67. const Cc = Components.classes;
  68. const Ci = Components.interfaces;
  69. const Cr = Components.results;
  70.  
  71. const CID = Components.ID("{ec7a6c20-e081-11da-8ad9-0800200c9a66}");
  72. const CONTRACT_ID = "@mozilla.org/browser/sessionstartup;1";
  73. const CLASS_NAME = "Browser Session Startup Service";
  74.  
  75. const STATE_RUNNING_STR = "running";
  76.  
  77. /* :::::::: Pref Defaults :::::::::::::::::::: */
  78.  
  79. // whether the service is enabled
  80. const DEFAULT_ENABLED = true;
  81.  
  82. // resume the current session at startup just this once
  83. const DEFAULT_RESUME_SESSION_ONCE = false;
  84.  
  85. // resume the current session at startup if it had previously crashed
  86. const DEFAULT_RESUME_FROM_CRASH = true;
  87.  
  88. function debug(aMsg) {
  89.   aMsg = ("SessionStartup: " + aMsg).replace(/\S{80}/g, "$&\n");
  90.   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
  91.                                      .logStringMessage(aMsg);
  92. }
  93.  
  94. /* :::::::: The Service ::::::::::::::: */
  95.  
  96. function SessionStartup() {
  97. }
  98.  
  99. SessionStartup.prototype = {
  100.  
  101.   // the state to restore at startup
  102.   _iniString: null,
  103.  
  104. /* ........ Global Event Handlers .............. */
  105.  
  106.   /**
  107.    * Initialize the component
  108.    */
  109.   init: function sss_init() {
  110.     this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
  111.                        getService(Ci.nsIPrefService).
  112.                        getBranch("browser.");
  113.     this._prefBranch.QueryInterface(Ci.nsIPrefBranch2);
  114.  
  115.     // if the service is disabled, do not init 
  116.     if (!this._getPref("sessionstore.enabled", DEFAULT_ENABLED))
  117.       return;
  118.  
  119.     // get file references
  120.     var dirService = Cc["@mozilla.org/file/directory_service;1"].
  121.                      getService(Ci.nsIProperties);
  122.     this._sessionFile = dirService.get("ProfD", Ci.nsILocalFile);
  123.     this._sessionFile.append("sessionstore.js");
  124.     
  125.     // only read the session file if config allows possibility of restoring
  126.     var resumeFromCrash = this._getPref("sessionstore.resume_from_crash", DEFAULT_RESUME_FROM_CRASH);
  127.     if (resumeFromCrash || this._doResumeSession()) {
  128.       // get string containing session state
  129.       this._iniString = this._readFile(this._sessionFile);
  130.       if (this._iniString) {
  131.         try {
  132.           // parse the session state into JS objects
  133.           var s = new Components.utils.Sandbox("about:blank");
  134.           var initialState = Components.utils.evalInSandbox(this._iniString, s);
  135.  
  136.           // set bool detecting crash
  137.           this._lastSessionCrashed =
  138.             initialState.session && initialState.session.state &&
  139.             initialState.session.state == STATE_RUNNING_STR;
  140.         // invalid .INI file - nothing can be restored
  141.         }
  142.         catch (ex) { debug("The session file is invalid: " + ex); } 
  143.       }
  144.     }
  145.     
  146.     // prompt and check prefs
  147.     this._doRestore = this._lastSessionCrashed ? this._doRecoverSession() : this._doResumeSession();
  148.     if (this._iniString && !this._doRestore) {
  149.       this._iniString = null; // reset the state string
  150.     }
  151.     if (this._getPref("sessionstore.resume_session_once", DEFAULT_RESUME_SESSION_ONCE)) {
  152.       this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
  153.     }
  154.     
  155.     if (this.doRestore()) {
  156.       // wait for the first browser window to open
  157.       var observerService = Cc["@mozilla.org/observer-service;1"].
  158.                             getService(Ci.nsIObserverService);
  159.       observerService.addObserver(this, "domwindowopened", true);
  160.     }
  161.   },
  162.  
  163.   /**
  164.    * Handle notifications
  165.    */
  166.   observe: function sss_observe(aSubject, aTopic, aData) {
  167.     var observerService = Cc["@mozilla.org/observer-service;1"].
  168.                           getService(Ci.nsIObserverService);
  169.  
  170.     switch (aTopic) {
  171.     case "app-startup": 
  172.       observerService.addObserver(this, "final-ui-startup", true);
  173.       break;
  174.     case "final-ui-startup": 
  175.       observerService.removeObserver(this, "final-ui-startup");
  176.       this.init();
  177.       break;
  178.     case "domwindowopened":
  179.       var window = aSubject;
  180.       var self = this;
  181.       window.addEventListener("load", function() {
  182.         self._onWindowOpened(window);
  183.         window.removeEventListener("load", arguments.callee, false);
  184.       }, false);
  185.       break;
  186.     }
  187.   },
  188.  
  189.   /**
  190.    * Removes the default arguments from the first browser window
  191.    * (and removes the "domwindowopened" observer afterwards)
  192.    */
  193.   _onWindowOpened: function sss_onWindowOpened(aWindow) {
  194.     var wType = aWindow.document.documentElement.getAttribute("windowtype");
  195.     if (wType != "navigator:browser")
  196.       return;
  197.     
  198.     var defaultArgs = Cc["@mozilla.org/browser/clh;1"].
  199.                       getService(Ci.nsIBrowserHandler).defaultArgs;
  200.     if (aWindow.arguments && aWindow.arguments[0] &&
  201.         aWindow.arguments[0] == defaultArgs)
  202.       aWindow.arguments[0] = null;
  203.     
  204.     var observerService = Cc["@mozilla.org/observer-service;1"].
  205.                           getService(Ci.nsIObserverService);
  206.     observerService.removeObserver(this, "domwindowopened");
  207.   },
  208.  
  209. /* ........ Public API ................*/
  210.  
  211.   /**
  212.    * Get the session state as a string
  213.    */
  214.   get state() {
  215.     return this._iniString;
  216.   },
  217.  
  218.   /**
  219.    * Determine if session should be restored
  220.    * @returns bool
  221.    */
  222.   doRestore: function sss_doRestore() {
  223.     return this._doRestore && this._iniString != null;
  224.   },
  225.  
  226. /* ........ Auxiliary Functions .............. */
  227.  
  228.   /**
  229.    * Whether or not to resume session, if not recovering from a crash.
  230.    * @returns bool
  231.    */
  232.   _doResumeSession: function sss_doResumeSession() {
  233.     return this._getPref("startup.page", 1) == 3 ||
  234.       this._getPref("sessionstore.resume_session_once", DEFAULT_RESUME_SESSION_ONCE);
  235.   },
  236.  
  237.   /**
  238.    * prompt user whether or not to restore the previous session,
  239.    * if the browser crashed
  240.    * @returns bool
  241.    */
  242.   _doRecoverSession: function sss_doRecoverSession() {
  243.     // do not prompt or resume, post-crash
  244.     if (!this._getPref("sessionstore.resume_from_crash", DEFAULT_RESUME_FROM_CRASH))
  245.       return false;
  246.  
  247.     // if the prompt fails, recover anyway
  248.     var recover = true;
  249.     // allow extensions to hook in a more elaborate restore prompt
  250.     // XXXzeniko drop this when we're using our own dialog instead of a standard prompt
  251.     var dialogURI = this._getPref("sessionstore.restore_prompt_uri");
  252.     
  253.     try {
  254.       if (dialogURI) { // extension provided dialog 
  255.         var params = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  256.                      createInstance(Ci.nsIDialogParamBlock);
  257.         // default to recovering
  258.         params.SetInt(0, 0);
  259.         Cc["@mozilla.org/embedcomp/window-watcher;1"].
  260.         getService(Ci.nsIWindowWatcher).
  261.         openWindow(null, dialogURI, "_blank", 
  262.                    "chrome,modal,centerscreen,titlebar", params);
  263.         recover = params.GetInt(0) == 0;
  264.       }
  265.       else { // basic prompt with no options
  266.         // get app name from branding properties
  267.         var brandStringBundle = this._getStringBundle("chrome://branding/locale/brand.properties");
  268.         var brandShortName = brandStringBundle.GetStringFromName("brandShortName");
  269.  
  270.         // create prompt strings
  271.         var ssStringBundle = this._getStringBundle("chrome://browser/locale/sessionstore.properties");
  272.         var restoreTitle = ssStringBundle.formatStringFromName("restoredTitle", [brandShortName], 1);
  273.         var restoreText = ssStringBundle.formatStringFromName("restoredMsg", [brandShortName], 1);
  274.         var buttonTitle = ssStringBundle.GetStringFromName("buttonTitle");
  275.         var cancelTitle = ssStringBundle.GetStringFromName("cancelTitle");
  276.  
  277.         var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  278.                             getService(Ci.nsIPromptService);
  279.  
  280.         // set the buttons that will appear on the dialog
  281.         var flags = promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
  282.                     promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
  283.                     promptService.BUTTON_POS_0_DEFAULT;
  284.         
  285.         var buttonChoice = promptService.confirmEx(null, restoreTitle, restoreText, 
  286.                                           flags, buttonTitle, cancelTitle, null, 
  287.                                           null, {});
  288.         recover = (buttonChoice == 0);
  289.       }
  290.     }
  291.     catch (ex) { dump(ex + "\n"); } // if the prompt fails, recover anyway
  292.     return recover;
  293.   },
  294.  
  295.   /**
  296.    * Convenience method to get localized string bundles
  297.    * @param aURI
  298.    * @returns nsIStringBundle
  299.    */
  300.   _getStringBundle: function sss_getStringBundle(aURI) {
  301.     var bundleService = Cc["@mozilla.org/intl/stringbundle;1"].
  302.                         getService(Ci.nsIStringBundleService);
  303.     var appLocale = Cc["@mozilla.org/intl/nslocaleservice;1"].
  304.                     getService(Ci.nsILocaleService).getApplicationLocale();
  305.     return bundleService.createBundle(aURI, appLocale);
  306.   },
  307.  
  308. /* ........ Storage API .............. */
  309.  
  310.   /**
  311.    * basic pref reader
  312.    * @param aName
  313.    * @param aDefault
  314.    * @param aUseRootBranch
  315.    */
  316.   _getPref: function sss_getPref(aName, aDefault) {
  317.     var pb = this._prefBranch;
  318.     try {
  319.       switch (pb.getPrefType(aName)) {
  320.       case pb.PREF_STRING:
  321.         return pb.getCharPref(aName);
  322.       case pb.PREF_BOOL:
  323.         return pb.getBoolPref(aName);
  324.       case pb.PREF_INT:
  325.         return pb.getIntPref(aName);
  326.       default:
  327.         return aDefault;
  328.       }
  329.     }
  330.     catch(ex) {
  331.       return aDefault;
  332.     }
  333.   },
  334.  
  335.   /**
  336.    * reads a file into a string
  337.    * @param aFile
  338.    *        nsIFile
  339.    * @returns string
  340.    */
  341.   _readFile: function sss_readFile(aFile) {
  342.     try {
  343.       var stream = Cc["@mozilla.org/network/file-input-stream;1"].
  344.                    createInstance(Ci.nsIFileInputStream);
  345.       stream.init(aFile, 0x01, 0, 0);
  346.       var cvstream = Cc["@mozilla.org/intl/converter-input-stream;1"].
  347.                      createInstance(Ci.nsIConverterInputStream);
  348.       cvstream.init(stream, "UTF-8", 1024, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  349.       
  350.       var content = "";
  351.       var data = {};
  352.       while (cvstream.readString(4096, data)) {
  353.         content += data.value;
  354.       }
  355.       cvstream.close();
  356.       
  357.       return content.replace(/\r\n?/g, "\n");
  358.     }
  359.     catch (ex) { } // inexisting file?
  360.     
  361.     return null;
  362.   },
  363.  
  364. /* ........ QueryInterface .............. */
  365.  
  366.   QueryInterface: function(aIID) {
  367.     if (!aIID.equals(Ci.nsISupports) && !aIID.equals(Ci.nsIObserver) && 
  368.       !aIID.equals(Ci.nsISupportsWeakReference) && 
  369.       !aIID.equals(Ci.nsISessionStartup)) {
  370.       Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
  371.       return null;
  372.     }
  373.     
  374.     return this;
  375.   }
  376. };
  377.  
  378. /* :::::::: Service Registration & Initialization ::::::::::::::: */
  379.  
  380. /* ........ nsIModule .............. */
  381.  
  382. const SessionStartupModule = {
  383.  
  384.   getClassObject: function(aCompMgr, aCID, aIID) {
  385.     if (aCID.equals(CID)) {
  386.       return SessionStartupFactory;
  387.     }
  388.     
  389.     Components.returnCode = Cr.NS_ERROR_NOT_REGISTERED;
  390.     return null;
  391.   },
  392.  
  393.   registerSelf: function(aCompMgr, aFileSpec, aLocation, aType) {
  394.     aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
  395.     aCompMgr.registerFactoryLocation(CID, CLASS_NAME, CONTRACT_ID, aFileSpec, aLocation, aType);
  396.  
  397.     var catMan = Cc["@mozilla.org/categorymanager;1"].
  398.                  getService(Ci.nsICategoryManager);
  399.     catMan.addCategoryEntry("app-startup", CLASS_NAME, "service," + CONTRACT_ID, true, true);
  400.   },
  401.  
  402.   unregisterSelf: function(aCompMgr, aLocation, aType) {
  403.     aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
  404.     aCompMgr.unregisterFactoryLocation(CID, aLocation);
  405.  
  406.     var catMan = Cc["@mozilla.org/categorymanager;1"].
  407.                  getService(Ci.nsICategoryManager);
  408.     catMan.deleteCategoryEntry( "app-startup", "service," + CONTRACT_ID, true);
  409.   },
  410.  
  411.   canUnload: function(aCompMgr) {
  412.     return true;
  413.   }
  414. }
  415.  
  416. /* ........ nsIFactory .............. */
  417.  
  418. const SessionStartupFactory = {
  419.  
  420.   createInstance: function(aOuter, aIID) {
  421.     if (aOuter != null) {
  422.       Components.returnCode = Cr.NS_ERROR_NO_AGGREGATION;
  423.       return null;
  424.     }
  425.     
  426.     return (new SessionStartup()).QueryInterface(aIID);
  427.   },
  428.  
  429.   lockFactory: function(aLock) { },
  430.  
  431.   QueryInterface: function(aIID) {
  432.     if (!aIID.equals(Ci.nsISupports) && !aIID.equals(Ci.nsIModule) &&
  433.         !aIID.equals(Ci.nsIFactory) && !aIID.equals(Ci.nsISessionStartup)) {
  434.       Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
  435.       return null;
  436.     }
  437.     
  438.     return this;
  439.   }
  440. };
  441.  
  442. function NSGetModule(aComMgr, aFileSpec) {
  443.   return SessionStartupModule;
  444. }
  445.